package org.school.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.school.dao.DingdanDao;
import org.school.dao.ShopDao;
import org.school.entity.*;
import org.school.dao.UserDao;
import org.school.service.UserService;
import org.school.staticException.PasswordIncorrectException;
import org.school.staticException.UserNotFoundException;
import org.school.types.Cai;
import org.school.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.xkzhangsan.time.formatter.DateTimeFormatterUtil.format;
import static com.xkzhangsan.time.formatter.DateTimeFormatterUtil.formatToDateStr;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2022-12-29 00:52:24
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;
    @Resource
    private DingdanDao dingdanDao;
    @Resource
    private ShopDao shopDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer id) {
        return this.userDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param user 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<User> queryByPage(User user, PageRequest pageRequest) {
        long total = this.userDao.count(user);
        return new PageImpl<>(this.userDao.queryAllByLimit(user, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        this.userDao.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        this.userDao.update(user);
        return this.queryById(user.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.userDao.deleteById(id) > 0;
    }

    @Override
    public message login(String UserName, String PassWord) throws UserNotFoundException, PasswordIncorrectException, NoSuchAlgorithmException {
        System.out.println(UserName);
        message newMsg = new message();
        newMsg.setType("用户");
        User loginUser=queryByName(UserName);
        if(loginUser==null){
            newMsg.setContent("该用户不存在");
            newMsg.setStatus(-1);
            return newMsg;

        }
        PassWord=MD5Utils.getMD5Str(PassWord);
        //如果查到了账号但密码不对
        if(!PassWord.equals(loginUser.getPassword())){
            newMsg.setContent("用户密码错误");
            newMsg.setStatus(-1);
           return newMsg;

        }
      String token = UUID.randomUUID().toString();//生成唯一标识,暂时不用
      User redisUser=loginUser;
      redisUser.setToken(token);
      String userStr= JSONObject.toJSONString(redisUser);
        redisTemplate.opsForValue().set("usertoken:"+redisUser.getToken(), userStr,80*10, TimeUnit.HOURS);

newMsg.setStatus(1);
newMsg.setContent(loginUser.getUsername());
newMsg.setToken(token);
        return newMsg;
    }

    @Override
    public message register(User user) throws NoSuchAlgorithmException {
        message mes=new message();
        User regUser=queryByName(user.getUsername());
        if(regUser!=null){
            mes.setContent("用户已存在");
            mes.setStatus(0);
            return mes;
        }
        if(user.getUsername()!=null&&user.getPassword()!=null) {
           user.setPassword(MD5Utils.getMD5Str(user.getPassword())); ;
           insert(user);
        }

        String token = UUID.randomUUID().toString();//生成唯一标识,暂时不用
        User redisUser=user;
        redisUser.setToken(token);
        String userStr= JSONObject.toJSONString(redisUser);
        redisTemplate.opsForValue().set("usertoken:"+redisUser.getToken(), userStr,80*10, TimeUnit.HOURS);
        mes.setType("用户");
        mes.setToken(token);
        mes.setStatus(1);
        mes.setContent("创建用户成功");
        return mes;
    }

    @Override
    public int order(Dingdan dd) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String date=format(new Date(),formatter);
        dd.setStarttime(date);
        dd.setStatus("进行中");
        int i=this.dingdanDao.insert(dd);
        List<Cai> list=dd.getOrder();
        String redisList=JSONObject.toJSONString(list);
        redisTemplate.opsForValue().set("order:"+dd.getId(),redisList);

        return i;
    }

    @Override
    public List<Dingdan> querryOrderByUser(String name) {
        List<Dingdan> list=dingdanDao.querryOrderByUser(name);
        for (Dingdan dingdan : list) {
            String s=redisTemplate.opsForValue().get("order:"+dingdan.getId());
            List<org.school.types.Cai> typelist=JSONObject.parseArray(s,org.school.types.Cai.class);
            dingdan.setOrder(typelist);
        }
        return list;
    }

    @Override
    public int completeOrderByUser(String name, Date date,String staus,int id) {
        Dingdan dd=dingdanDao.queryById(id);
        if(!name.equals(dd.getUser())){
            return -1;
        }
        return this.dingdanDao.updateByUser(id,name,date,staus);
    }

    @Override
    public List<Shop> queryShopInfo() {
        return this.shopDao.queryShopInfo();
    }

    @Override
    public List<Shop> queryListShopInfo(String name) {
        return null;
    }

    @Override
    public PageInfo<Shop> findShopInfo(int pageNum, int size) {
        // TODO Auto-generated method stub
        PageHelper.startPage(pageNum, size);
        List<Shop> lists = this.shopDao.queryShopInfo();
        PageInfo<Shop> pageInfo = new PageInfo<Shop>(lists);
        return pageInfo;
    }

    @Override
    public PageInfo<Shop> findListShopInfo(String name,int pageNum, int size) {//分页模糊查询
        // TODO Auto-generated method stub
        PageHelper.startPage(pageNum, size);
        List<Shop> lists = this.shopDao.queryListShopInfo(name);
        PageInfo<Shop> pageInfo = new PageInfo<>(lists);
        return pageInfo;
    }

    private User queryByName(String userName) {
return this.userDao.queryByName(userName);
    }
}
